/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.alerts;

import org.geoscheduler.android.activities.AlertPopup;
import org.geoscheduler.model.Event;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;

/**
 * FIXME [paja]: comment me
 * 
 * @author paja
 */
public class AlertService extends Service {

	private static final String LOGTAG = "AlertService";
	
	private Location checkedLocation;
	private int lat;
	private int lon;
	
	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	/**
	 * Object receiving interaction from client 
	 */
	private final IBinder mBinder = new Binder() {
		@Override
		protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
			return super.onTransact(code, data, reply, flags);
		}
	};
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d(LOGTAG, LOGTAG + ": activity started");
		
		checkedLocation = (Location) intent.getExtras().get("location");
		lat = new Double(checkedLocation.getLatitude() * 1E6).intValue();
		lon = new Double(checkedLocation.getLongitude() * 1E6).intValue();
		
		Log.d(LOGTAG, LOGTAG + ": location (" + lat	+ "," + lon	+ ")");

		Thread thr = new Thread(null, mTask, this.getClass().getSimpleName());
		thr.start();
	}
	
	
	Runnable mTask = new Runnable() {
		public void run() {
			synchronized (mBinder) {
				try {
					Event e = AlertHelper.findActualEvent(AlertService.this, lat, lon);
					
					if (e != null) {
						Intent i = new Intent(AlertService.this, AlertPopup.class);
						i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						i.putExtra(AlertPopup.class.getName() + AlertPopup.PAR_EVENT_ID, e.getId());
						
						startActivity(i);
					}
				} catch (Exception e) {
					Log.e(LOGTAG, LOGTAG + ": Failed to find actual event.", e);
				}
			}

			AlertService.this.stopSelf();
		}
	};

}
